var Md5 = require("./md5.js");
module.exports = {
	// apiServer: 'http://192.168.31.122/api/',
	// mainapiServer: 'http://192.168.31.122/api/',
	// imgServer: 'http://192.168.31.122',
	// nServer:'http://192.168.31.122/',
	
	// obs:'http://192.168.31.122/',
	
	
	apiServer: 'https://lizhili.biaotian.ltd/api/',
	mainapiServer: 'https://lizhili.biaotian.ltd/api/',
	imgServer: 'https://lizhili.biaotian.ltd',
	nServer:'https://lizhili.biaotian.ltd/',
	
	obs:'https://lizhili.biaotian.ltd/',
	to_time: function(timestamp, a) {
		let date;
		if(timestamp > 100000000000){
			date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
		}else{
			date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
		}
		let Y = date.getFullYear();
		let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
		let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
		let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
		let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
		let s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
		if (a == 1) {
			return M + '月' + D + '日  ' + h + '时' + m + '分'
		} else if (a == 2) {
			return Y + '-' + M + '-' + D + '  ' + h + ':' + m + ':' + s;
		} else if (a == 3) {
			return M + '.' + D;
		} else if (a == 4) {
			return M + '月' + D + '日';
		} else if (a == 5) {
			return Y + '-' + M + '-' + D;
		} else if (a == 6) {
			return Y + '年' + M + '月' + D + '日  ' + h + '时' + m + '分' + s + '秒';
		}
	},
	encrypted: function(obj) {
		var newkey = Object.keys(obj).sort();
		var newObj = {}; //创建一个新的对象，用于存放排好序的键值对
		for (var i = 0; i < newkey.length; i++) { //遍历newkey数组
			newObj[newkey[i]] = obj[newkey[i]]; //向新创建的对象中按照排好的顺序依次增加键值对
		}
		var zhi = ''
		for (let i in newObj) {
			//zhi += '&' + i + '=' + encodeURI(newObj[i])
			zhi += '&' + i + '=' + this.fixedEncodeURIComponent(newObj[i])
		}
	//	var reg = new RegExp('/', "g")
		// zhi = zhi.replace(/\//g, '%2F');
		// zhi = zhi.replace(/:/g, '%3A');
		// zhi = zhi.replace(/,/g, '%2C');
		// zhi = zhi.replace(/\$/g, '%24');
		// zhi = zhi.replace(/%20/g, '+');
		zhi = zhi.substr(1)
	//console.log(zhi);
		newObj.app_key = Md5.md5(zhi + '197686741c09329446b110070f88f54d') //app_key 在这里
		return newObj; //返回排好序的新对象
	},
	fixedEncodeURIComponent: function  (str) {
	  return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
	    return '%' + c.charCodeAt(0).toString(16);
	  });
	},
	post : function(url, data, contentType,success, fail){
		if(!fail){fail = () => {this.msg("网络请求失败");}}
		data.time=Date.parse(new Date())/1000;
		let sha_time=uni.getStorageSync('shua_time')
		let sha_token=uni.getStorageSync('shua_token')
		if(!sha_time || !sha_token || data.time>=sha_time){
			//刷新 token
			uni.request({
			    url: uni.common.apiServer + 'index', 
			    data: {
			        lizhili: '0d89b868429be6158ba1ebc0f7c073de',
					type:'shua_token',
					time:data.time,
					token:Md5.md5(String(data.time))
			    },
				method:'POST',
			    header: {'token': Md5.md5(String(data.time)),'content-type':'application/json'},
			    success: (res) => {
			        let re=res.data;
					if(re.code==10004){
						uni.setStorageSync('shua_time', re.shua_time);
						uni.setStorageSync('shua_token', re.shua_token);
						data.lizhili= re.shua_token;
						this.true_post(url, data, contentType,success, fail)
					}else{
						this.msg('刷新token错误')
					}
			       
			    }
			});
		}else{
			data.lizhili= uni.getStorageSync('shua_token');
			this.true_post(url, data, contentType,success, fail)
		}
	},
	true_post:function(url, data, contentType,success, fail){
		if(contentType){
			data.token=uni.getStorageSync('token');
		}
		if(url.substr(url.length-5)!='index' && !data.token){
			data.token=uni.getStorageSync('token');
		}
		
		data=this.encrypted(data);
		let headers={};
		headers['token'] = '461f6924bed805723485e08b985049ebbb3a9774';
		headers['content-type'] = 'application/x-www-form-urlencoded';
		// if(!headers){headers={};}
		// if(!contentType){contentType = 'form';}
		// switch(contentType){
		// 	case "form" : 
		// 	headers['content-type'] = 'application/x-www-form-urlencoded';
		// 	break;
		// 	case "json" : 
		// 	headers['content-type'] = 'application/json';
		// 	break;
		// 	default :
		// 	headers['content-type'] = 'application/x-www-form-urlencoded';
		// }
		uni.request({
			url      : url,
			data     : data,
			method   : "POST",
			dataType : "json",
			header   : headers,
			success  : (res) => {
				if(res.data.code==10001 || res.data.code==10002){
					 this.msg(res.data.message)
				}
				if(res.data.code==10000){
					 uni.removeStorageSync('token');
					 uni.reLaunch({
					     url: '/pages/my/login'
					 });
				}
				success(res.data);},
			fail     : fail,
			complete : () => {}
		});
	},
	msg : function(msg){uni.showToast({title:msg, icon:"none"});},
	back: function(msg){
		if(msg){
			uni.showToast({title:msg, icon:"none"});
			setTimeout(()=>{
				uni.navigateBack()
			},1000)
		}else{
			uni.navigateBack()
		}
	},
	//uploadCards 使用方法
	//async submit(e) {
	// let w;
	// 	w=	await common.uploadCards(this.idCard1);
	// 	if(w && w.code==1){
	// 		this.idCard11=w.data
	// 	}
	// }
	uploadCards: function(data,type='uploadCards') {
		const token = uni.getStorageSync('token');
		return	uni.uploadFile({
			url: this.apiServer + 'update', 
			filePath: data,
			name: 'file',
			formData: {
				lizhili: '0d89b868429be6158ba1ebc0f7c073de',
				type: type,
				token: token
			},
		})
		.then(data => {
			var [err, res]  = data;
			if(err){
				console.log('上传出错误了:',err);
				return false
			}
			return JSON.parse(res.data);
		})
	},
	
	is_login:function(){
		const token = uni.getStorageSync('token');
		if (token) {
			return new Promise((resolve) => {
			   this.post(
			   	this.apiServer + 'index',
			   	{
			   		type: 'get_my_check',
			   	},
			   	true,
			   	res => {
			   		if (res.code == 1) {
			   			resolve(true);
			   		}else{
			   			resolve(false);
			   		}
			   	},
			   	e => {
			   		console.log(e);
			   	}
			   );
			});
		}else{
			return false;
		}
	}
}
